package com.example.springboot.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/7/25 21:08
 */
public class JwtHelper {
    /**
     * 过期时间
     */
    private static long tokenExpiration = 24 * 60 * 60 * 1000;
    /**
     * 签名秘钥
     */
    private static String tokenSignKey = "123456";
    public static String createToken(){
        String token = Jwts.builder()
                .setSubject("czk")
                .claim("name", "czk")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS256, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }
    /**
     * 根据token字符串得到用户名称
     *
     * @param token
     * @return
     */
    public static String getUserName(String token) {
        if (StringUtils.isEmpty(token)) return "";

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("name");
    }

    public static void main(String[] args) {
        String token = createToken();
        System.out.println(token);
        System.out.println(getUserName(token));
    }
}
